from .tools import Tools
from src.log import logger

class InterViewer:
    def __del__(self):
        pass
    def __init__(self,name,cnx):
        self.name = name
        self.cnx = cnx
        self.prefix = '/home/iroan/labelservice/Files/'

    def get_test_number(self):
        cur = self.cnx.cursor()
        cur.execute("select count(CaseID) from zzxs_ftr where username = %s",(self.name,))
        test_total_number = 0
        for i in cur:
            test_total_number = i[0]
            logger.debug('self.test_total_number=%s',test_total_number)
        cur.close()
        return test_total_number

    def get_during_time(self):
        suffix = '/Labelled'
        file_path = self.prefix + self.name.strip() + suffix
        import os
        lists = os.listdir(file_path)
        start_time = os.path.getmtime(file_path + '/' + lists[0])
        end_time = start_time
        for item in lists:
            temp = os.path.getmtime(file_path + '/' + item)
            if temp > end_time:
                end_time = temp
            elif temp < start_time:
                start_time = temp

        return (end_time,start_time)

    def get_end_test_time(self):
        return self.get_during_time()[0]

    def get_right_number(self):
        # 功能：获得做对题目的数量
        # 实现：比较interviewer对于题目的选择和标准答案，如果匹配，则此做对，统计结果自增1
        tool = Tools()
        right_answer = tool.getTestRightAnswer()
        case_id = self.data

        logger.debug('读取到的标准答案的数量=%s' % (right_answer.__len__()))
        logger.debug('读取到的测试则做题的数量=%s' % (case_id.__len__()))


    def get_statistics(self):
        # interviewerID    做题总数    作对数量    用时（分钟）    准确率（%）    相对准确率（除以时间）    备注
        statistics = {}
        statistics['interviewerID'] = self.name
        statistics['test_total_number'] = self.get_test_number()
        statistics['right_answer_number'] = self.get_right_answer_number()
        statistics['end_time'] = self.get_during_time()[0]
        statistics['start_time'] = self.get_during_time()[1]
        statistics['during_time'] = (statistics['end_time'] - statistics['start_time'])/60
        statistics['right_rate'] = statistics['right_answer_number'] / statistics['test_total_number']
        statistics['relative_right_rate'] = statistics['right_answer_number'] / statistics['during_time']

        return statistics

    def get_right_answer_number(self):
        # 1. 得到interviewer的题目的answer
        # 2. 到数据库中查询标准答案的anser
        # 3. 如果两个值相等，则题目做对了
        # 4. 记录做对的题目的数量

        cur = self.cnx.cursor()
        num = self.get_test_number()

        cur.execute("select CaseID,CrimeCharacter from zzxs_ftr where username = %s;",(self.name,))
        tests = tuple(cur)

        right_num = 0;

        for test_item in tests:
            cur.execute("select Answer from right_answer where CaseID = %s;", (test_item[0],))
            for i in cur:
                if test_item[1] == int(i[0]):
                    right_num += 1
        cur.close()
        return right_num
